package com.carboncntr.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;

import com.carboncntr.helper.CustomerHelper;
import com.carboncntr.struts.form.LoginForm;
import com.carboncntr.tables.Customer;

public class LoginAction extends DispatchAction {
	public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
		return mapping.findForward("begin");
	}
	public ActionForward submit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
		LoginForm loginForm = (LoginForm)form;
		Customer c = CustomerHelper.getCustomerLogin(loginForm.getUsername(), loginForm.getPassword());
		HttpSession session = (HttpSession)request.getSession();
		if(c != null) {
			
			session.setAttribute("Customer", c);
			return mapping.findForward("success");
		}else {
			ActionMessages messages = new ActionMessages();
			messages.add("invalid.login", new ActionMessage("invalid.login"));
			saveMessages(request, messages);
			
			return mapping.findForward("failure");
		}
		
	}
}
